package com.solotiger.okex.controller;



import com.solotiger.okex.common.contants.GlobalContants;
import com.solotiger.okex.common.result.Result;
import com.solotiger.okex.common.result.ResultFactory;
import com.solotiger.okex.domain.OkexUser;
import com.solotiger.okex.domain.OkexUserToken;
import com.solotiger.okex.domain.vo.UserVo;
import com.solotiger.okex.service.OkexUserService;
import com.solotiger.okex.service.OkexUserTokenService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;

/**
 * 登录相关
 */
@RestController
@RequestMapping("/login")
@CrossOrigin
public class LoginController extends AbstractController {

    private static final String ADMIN = "admin";

    @Autowired
    private OkexUserService okexUserService;
    @Autowired
    private OkexUserTokenService okexUserTokenService;

    /**
     * 登录
     *
     * @param username
     * @param password
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/login")
    public Result login(String username, String password) {
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResultFactory.INSTANCE.error("账号或密码不正确");
        }
        //用户信息
        OkexUser user = okexUserService.findByName(username);
        //管理员登录
//        if (ADMIN.equals(username)) {
//            user =
//        } else {
//            if (ValidatorUtil.isEmail(username)) {
//                user = egsUserService.findByEmail(username);
//            } else {
//                user = egsUserService.findByTelephone(username);
//            }
//        }

        //账号不存在、密码错误
        if (user == null || !user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())) {
            return ResultFactory.INSTANCE.error("账号或密码不正确");
        }

        //账号锁定
        if (user.getStatus() == GlobalContants.STATE_USER_DISABLE) {
            return ResultFactory.INSTANCE.error("账号已被锁定,请联系管理员");
        }
        UserVo userVo = new UserVo();
        try {
            BeanUtils.copyProperties(userVo, user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //生成token，并保存到数据库
        OkexUserToken sysUserToken = okexUserTokenService.createToken(user.getUserId());
        userVo.setToken(sysUserToken.getToken());
        userVo.setRefreshToken(sysUserToken.getRefreshToken());
        userVo.setExpireTime(sysUserToken.getExpireTime());
        return ResultFactory.INSTANCE.success(userVo);
    }


    /**
     * 退出
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Result logout() {
        okexUserTokenService.logout(getUserId());
        return ResultFactory.INSTANCE.success();
    }
}
